﻿namespace EasyWeb.Configuration
{
    using System;
    using System.IO;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Linq;

    public static class EWConfigurationManager
    {
        public async static Task<EWFieldConfigurationCollection> GetFieldsAsync()
        {
            var list = new EWFieldConfigurationCollection();

            var xml = await ReadXmlAsync("EWFieldDefinitions.xml");
            foreach (var element in xml.Root.Elements("FieldDefinition"))
            {
                list.Add(new EWFieldConfiguration()
                {
                    Id = new Guid(element.Attribute("Id").Value),
                    Type = Type.GetType(element.Element("Type").Value),
                    DesignTemplate = element.Element("DesignTemplate").Value,
                });
            }

            return list;
        }

        public async static Task<EWNavigationNodeCollection> GetNavigationsAsync()
        {
            var results = new EWNavigationNodeCollection();

            var xml = await ReadXmlAsync("EWNavigation.xml");

            BuildNavigationNodes(results, xml.Root);

            return results;
        }

        private static async Task<XDocument> ReadXmlAsync(string file)
        {
            var xml = default(string);

            var directory = EWHelpers.Environment.MapPath("~/App_Data");
            file = Path.Combine(directory, file);
            using (var reader = new StreamReader(file, Encoding.UTF8))
            {
                xml = await reader.ReadToEndAsync();
            }

            return XDocument.Parse(xml, LoadOptions.None);
        }

        private static void BuildNavigationNodes(EWNavigationNodeCollection collection, XElement parentElement)
        {
            foreach (var childElement in parentElement.Elements("Node"))
            {
                var node = new EWNavigationNode();

                var attribute = default(XAttribute);

                node.Id = childElement.Attribute("Id").Value;

                node.Name = childElement.Attribute("Name").Value;

                attribute = childElement.Attribute("ResourceType");
                if (attribute != null)
                {
                    node.ResourceType = Type.GetType(attribute.Value, true);
                }

                attribute = childElement.Attribute("Url");
                if (attribute != null)
                {
                    node.Url = attribute.Value;
                }

                attribute = childElement.Attribute("Icon");
                if (attribute != null)
                {
                    node.Icon = attribute.Value;
                }

                collection.Add(node);

                BuildNavigationNodes(node.Nodes, childElement);
            }
        }
    }
}
